const Koa = require('koa');
const path = require('path');
const app = new Koa();
const fs = require('fs');
app.use(async ctx => {
    const { url } = ctx;

    if (url === '/') {
        console.log('url', url);
        console.log('ctx', ctx);
        ctx.type = 'text/html'
        let content = fs.readFileSync('./index.html', 'utf-8');
        content = content.replace(
            "<script ",
            `
            <script>
            window.process = {env: { NODE_ENV: 'dev' }}
            </script>
            <script
            `
        );
        ctx.body = content;
    } else if (url.endsWith('.js')) {
        console.log('url', url);
        // js文件
        const p = path.resolve(__dirname, url.slice(1))
        ctx.type = 'application/javascript';
        const content = fs.readFileSync(p, 'utf-8');
        //  import xx from 'xxx'  => '/@modules/xxx';
        ctx.body = rewriteImport(content)
    } else if (url.startsWith('/@modules/')) {
        // TODO /@modules/
        // @modules/vue ==> node_modules/vue => esmodule 的入口
        const prefix = path.resolve(__dirname, 'node_modules', url.replace('/@modules/', ''));
        console.log('prefix', prefix);
        const module = require(prefix + '/package.json').module;
        const p = path.resolve(prefix, module);
        const ret = fs.readFileSync(p, 'utf-8');
        ctx.type = 'application/javascript';
        ctx.body = rewriteImport(ret);
    }

});

let listens = 3300;

app.listen(listens, () => {
    console.log(`监听端口${listens} `);
})


function rewriteImport(content) {
    return content.replace(/ from ['|"]([^'"]+)['|"]/g, function (s0, s1) {
        //  ../  / 开头的 ，都是相对路径
        if (s1[0] !== '.' && s1[1] !== "/") {
            return `from '/@modules/${s1}'`
        } else {
            return s0
        }
    })
}



